package com.seaboxdata.jt809;

import com.seaboxdata.jt809.common.util.PropertiesUtil;
import com.seaboxdata.jt809.handle.JT809ServerInitialzer;
import com.seaboxdata.jt809.kafka.JT809Packet0x1202MessageConsumer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Author: dfjx
 * @Date: 2020/7/8 16:47
 * @Version 1.0
 * @Describe: 启动类
 */
public class JT809Server {

    private static Logger log = LoggerFactory.getLogger(JT809Server.class);

    private static int PORT;

    public static void main(String[] args) {
        log.info("args -> {}", args);
        // 因生产环境需要配置--spring.profiles.active=prod,
        // 此工程不能自动切环境,手动设置这个参数,在PropertiesUtil中取出并设置对应的配置文件
        if (args.length > 0) {
            for (String s : args) {
                if (s.indexOf("=") != -1) {
                    String[] str = s.split("=");
                    log.info("str {}", str[0]);
                    if ("--spring.profiles.active".equals(str[0]) || "-Dspring.profiles.active".equals(str[0])) {
                        System.setProperty(str[0], str[1]);
                    }
                }
            }
        }
        PORT = Integer.parseInt(PropertiesUtil.getProperty("port", "9090"));
        NioEventLoopGroup boosGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        final ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap
                .group(boosGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.TCP_NODELAY, true)
                .childHandler(new JT809ServerInitialzer());
        bind(serverBootstrap, PORT);
        //读取kafka线程 gps车辆定位
        Thread packet0x1202Consumer = new Thread(new Runnable() {
            @Override
            public void run() {
                log.info("JT809Server:车辆定位读取kafka线程启动");
                JT809Packet0x1202MessageConsumer cosumer = new JT809Packet0x1202MessageConsumer();
                cosumer.getMessage();
                log.warn("JT809Server:kafka consumer thread down");
            }
        });
        packet0x1202Consumer.start();
    }

    private static void bind(final ServerBootstrap serverBootstrap, int port) {
        serverBootstrap.bind(port).addListener(future -> {
            if (future.isSuccess()) {
                log.info("JT809Server在端口：{}启动成功!", port);
                //不自己定时删除
                /*  CommonUtils.del0x1202DataTimer(); // 定时删除车辆定位数据*/
//                CommonUtils.del0x1402DataTimer(); //定时删除车辆报警数据
            } else {
                log.error("JT809Server在端口：{}启动失败!", port);
            }
        });
    }
}
